//
//  GoodsListManagerViewController.m
//  BaishidaiShop
//
//  Created by mac book on 2019/1/22.
//  Copyright © 2019年 sy. All rights reserved.
//

#import "GoodsListManagerViewController.h"
#import "PushGoodsViewController.h"


#import "GoodsListManagerTableViewCell.h"
#import "ShopManagerAlertView.h"


#define HeaderView_Height  100/HEIGHT_6S_SCALE
#define  CellIdentifier  @"GoodsListCell"

@interface GoodsListManagerViewController ()<GoodsListManagerDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong) Pager* page;
@property(nonatomic,strong) UIView* headerView;
@property(nonatomic,strong) UIButton* typeBtn;
@property(nonatomic,strong) UIButton* searchBtn;
@property(nonatomic,strong) NSMutableArray* selectedArray;
@property(nonatomic,assign) BOOL  isSelected;
@property(nonatomic,strong) NSString  *type;

@property(nonatomic,strong) GoodsModel* currentGoods;

@end

@implementation GoodsListManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.navigationItem.title =  @"商品管理";
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 60, 25);
    [rightButton setTitle:@"发布商品" forState:UIControlStateNormal];
    [rightButton setTitleColor:getColor(greenBackColor) forState:UIControlStateNormal];
    rightButton.titleLabel.font = kFontNameSize(14);
    [rightButton addTarget:self action:@selector(rightButton) forControlEvents:UIControlEventTouchUpInside];
    //添加到导航条
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.isSelected = NO;
    [self querySelectData];
    [self creatTableView];
    
    
}
-(void)rightButton{
    
    PushGoodsViewController * controller = [[PushGoodsViewController alloc]init];
    [self.navigationController pushViewController:controller animated:YES];
}
-(void)creatTableView{
    
    [self creatHeaderView];

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.headerView.frame), SCREEN_WIDTH,  CGRectGetHeight(self.view.frame) -NAVGATIONBAR_HEIGHT - CGRectGetMaxY(self.headerView.frame)) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
    
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    [self.tableView registerClass:[GoodsListManagerTableViewCell class] forCellReuseIdentifier:CellIdentifier];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
-(void)creatHeaderView{
    
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HeaderView_Height)];
    [self.view addSubview:self.headerView];
    //self.headerView.backgroundColor = [UIColor whiteColor];
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.text = @"店铺分类";
    //    titleLabel.textColor = [UIColor grayColor];
    titleLabel.font = kFontNameSize(15);
    [self.headerView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(100);
        make.left.equalTo(self.headerView).mas_offset(20);
        make.top.equalTo(self.headerView);
    }];
    
    UIImageView *arrowImageView =[[UIImageView alloc] init];
    arrowImageView.image = [UIImage imageNamed:@"icon_arrowright"];
    arrowImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.headerView addSubview:arrowImageView];
    [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.headerView).offset(-12);
        make.centerY.equalTo(titleLabel);
        make.size.mas_equalTo(CGSizeMake(20, 20));
        
    }];
    
    
    self.typeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.typeBtn addTarget:self action:@selector(typeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    self.typeBtn.titleLabel.font= kFontNameSize(15);
    self.typeBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.headerView addSubview:self.typeBtn];
    [self.typeBtn setTitle:@"请选择店铺分类" forState:UIControlStateNormal];
    [self.typeBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [self.typeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(titleLabel);
        make.left.equalTo(titleLabel.mas_right);
        make.right.equalTo(arrowImageView.mas_left);
    }];
    
    
    
    self.searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.searchBtn addTarget:self action:@selector(searchBtnAction) forControlEvents:UIControlEventTouchUpInside];
    self.searchBtn.layer.masksToBounds = YES;
    self.searchBtn.layer.cornerRadius = 5;
    self.searchBtn.titleLabel.font= kFontNameSize(15);
    [self.headerView addSubview:self.searchBtn];
    [self.searchBtn setTitle:@"查询" forState:UIControlStateNormal];
    self.searchBtn.backgroundColor=  getColor(greenBackColor);
    [self.searchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(titleLabel.mas_bottom);
        make.bottom.equalTo(self.headerView).mas_offset(-10);
        make.right.equalTo(self.headerView).mas_offset(-30);
        make.left.equalTo(self.headerView).mas_offset(30);
    }];
    
}
-(void)querySelectData{

    [self showHUD];
    NSDictionary* arg = @{@"ince":@"getshopcat",
                          @"sid":[UserHandle shareInstance].userId,
                          @"parent_id":@"0"
                          };
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        [self hidHUD];
        NSLog(@"data = %@",data);
        NSInteger flag = [[data objectForKey:@"ret"]integerValue];
        if(flag == 200){
            NSArray *list = [data objectForKey:@"data"];
            self.selectedArray = [GoodsModel mj_objectArrayWithKeyValuesArray:list];
            
            [self refreshDataSource];
            
        }else{
            ShowMessage(data[@"msg"]);
        }
        
    } failure:^(NSError *error) {
        [self hidHUD:@"网络异常"];
    }];
    
}

-(void)typeBtnAction{

    NSMutableArray *array = [NSMutableArray array];
    for (GoodsModel *model in self.selectedArray) {
        [array addObject:model.cat_name];
    }
    [CGXPickerView showStringPickerWithTitle:@"店铺分类" DataSource:array DefaultSelValue:array.firstObject IsAutoSelect:NO Manager:nil ResultBlock:^(id selectValue, id selectRow) {
        NSLog(@"%@",selectValue);
        NSLog(@"selectRow = %@",selectRow);
        NSInteger index = [selectRow integerValue];
        GoodsModel *model = self.selectedArray[index];
        self.type = [NSString stringWithFormat:@"%@",model.cat_id];
        [self.typeBtn setTitle:[NSString stringWithFormat:@"%@",selectValue] forState:UIControlStateNormal];
        [self.typeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];


    }];
}

-(void)searchBtnAction{
    
    if ([self.typeBtn.titleLabel.text rangeOfString:@"选择"].location == NSNotFound) {
        
        self.isSelected = YES;
        self.page.pageIndex = 1;
        [self getData];
        
    }else{
        
        ShowMessage(@"请选择店铺分类");
        
    }
    
}
#pragma mark  - Data Source
-(void)getData{
    
    NSDictionary *arg = [NSDictionary dictionary];
    
    if (self.isSelected) {
        arg = @{@"ince":@"get_shop_foods",
                @"type":self.type,
                @"sid":[UserHandle shareInstance].userId,
                @"page":[WMHelper integerConvertToString:self.page.pageIndex]
                };
    }else{
        arg = @{@"ince":@"get_shop_foods",
                @"sid":[UserHandle shareInstance].userId,
                @"page":[WMHelper integerConvertToString:self.page.pageIndex]
                };
        
    }
    
    [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
        NSLog(@"商品管理 = %@",data);
        
        if(self.page.pageIndex == 1){
            [self.page.arrayData removeAllObjects];
        }
        NSInteger flag = [[data objectForKey:@"ret"]integerValue];
        if(flag == 200){
            self.page.recordCount = [[data objectForKey:@"count"] integerValue];
            self.page.pageSize = [[data objectForKey:@"number"]integerValue];
            NSInteger empty = self.page.recordCount % self.page.pageSize;
            if(empty == 0){
                self.page.pageCount = self.page.recordCount/self.page.pageSize;
            }else{
                self.page.pageCount = self.page.recordCount/self.page.pageSize+1;
            }
            
            NSMutableArray *tempArr = [GoodsModel mj_objectArrayWithKeyValuesArray:[data objectForKey:@"list"]];
            [ self.page.arrayData addObjectsFromArray:tempArr];

        }else{
            [self alertHUD:[data objectForKey:@"msg"]];
        }
        [self.tableView reloadData];
        if(self.page.pageCount<=self.page.pageIndex){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        if(self.page.pageIndex==1){
            [self.tableView.mj_header endRefreshing];
        }
        
    } failure:^(NSError *error) {
        [self alertHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];

}
-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page.pageIndex = 1;
        [weakSelf getData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        weakSelf.page.pageIndex ++;
        [weakSelf getData];
    }];
    [self.tableView.mj_header beginRefreshing];
}


#pragma mark - tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.page.arrayData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodsListManagerTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    cell.goodsModel = self.page.arrayData[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodsModel* item = self.page.arrayData[indexPath.row];
    CGFloat width = SCREEN_WIDTH - 150.f;
    CGFloat height = [WMHelper calculateTextHeight:item.name font:[UIFont systemFontOfSize:14.f] width:width];
    if(height>35.f){
        return 35.f+height;
    }
    return 70.f;
}

#pragma mark - GoodsListManagerDelegate
-(void)updateGoodsImage:(GoodsModel*)goodsModel{
    if(goodsModel){
        self.currentGoods = goodsModel;
        [self updateAvatarImage];
    }
    
}
-(void)updateGoodsTitle:(GoodsModel*)goodsModel{
    if(goodsModel){
        self.currentGoods = goodsModel;
        ShopManagerAlertView *alertView = [[ShopManagerAlertView alloc] initAlertWithType:ShopManagerTitle withText:goodsModel.name];
        //            __weak typeof(alertView) weakAlert = alertView;
        alertView.resultIndex = ^(NSString * _Nonnull changeText) {
            NSDictionary* arg =  @{@"ince":@"set_shop_name",
                                   @"sid":[UserHandle shareInstance].userId,
                                   @"fid": self.currentGoods.fid,
                                   @"name":changeText
                                   };
            [self showHUD];
            [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
                [self hidHUD];
                NSLog(@"data = %@",data);
                NSInteger flag = [[data objectForKey:@"ret"]integerValue];
                if(flag == 200){
                    
                    NSString* name = [data objectForKey: @"goods_name"];
                    self.currentGoods.name = name;
                    [self.tableView reloadData];
                    
                }else{
                    ShowMessage([data objectForKey:@"msg"]);
                }
                
            } failure:^(NSError *error) {
                [self hidHUD:@"网络异常"];
            }];

        };
        [alertView showAlertView];

    }
    
}
-(void)updateGoodsPrice:(GoodsModel*)goodsModel{
    if(goodsModel){
        self.currentGoods = goodsModel;
        ShopManagerAlertView *alertView = [[ShopManagerAlertView alloc] initAlertWithType:ShopManagerPrice withText:self.currentGoods.price];
        //            __weak typeof(alertView) weakAlert = alertView;
        alertView.resultIndex = ^(NSString * _Nonnull changeText) {
            NSDictionary* arg =  @{@"ince":@"set_shop_foodprice",
                                   @"sid":[UserHandle shareInstance].userId,
                                   @"fid": self.currentGoods.fid,
                                   @"price":changeText
                                   };
            [self showHUD];
            [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
                [self hidHUD];
                NSLog(@"data = %@",data);
                NSInteger flag = [[data objectForKey:@"ret"]integerValue];
                if(flag == 200){
                    NSString* price = [data objectForKey: @"price"];
                    NSString* checkPrice = [data objectForKey: @"check_price"];
                    self.currentGoods.price = price;
                    self.currentGoods.check_price = checkPrice;
                    [self.tableView reloadData];
                    
                }else{
                    ShowMessage([data objectForKey:@"msg"]);
                }
                
            } failure:^(NSError *error) {
                [self hidHUD:@"网络异常"];
            }];
        };
        
        [alertView showAlertView];

    }
}
-(void)publishGoods:(GoodsModel*)goodsModel{
    if(goodsModel){
        self.currentGoods = goodsModel;
        NSString* empty = [NSString stringWithFormat: @"您确认要%@该商品吗？",[self.currentGoods.status integerValue]==0? @"上架": @"下架"];
        UIAlertController *av = [UIAlertController alertControllerWithTitle:empty message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSString* status = [self.currentGoods.status integerValue]==0? @"1": @"0";
            NSDictionary* arg =  @{
                                   @"ince":@"set_shop_foodstatus",
                                   @"sid":[UserHandle shareInstance].userId,
                                   @"fid": self.currentGoods.fid,
                                   @"status":status
                                   };
            
            [self showHUD];
            [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
                [self hidHUD];
                NSLog(@"data = %@",data);
                NSInteger flag = [[data objectForKey:@"ret"]integerValue];
                if(flag == 200){
                    ShowMessage([data objectForKey:@"msg"]);

                }else{
                    ShowMessage([data objectForKey:@"msg"]);
                }
                self.currentGoods = nil;
                [self.tableView.mj_header beginRefreshing];
                
            } failure:^(NSError *error) {
                [self hidHUD:@"网络异常"];
            }];
        
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];
        [av addAction:action1];
        [av addAction:action2];
        [self presentViewController:av animated:YES completion:nil];

    }
}

#pragma mark - 上传头像
- (void)updateAvatarImage
{
    
    self.navigationController.navigationBar.hidden = NO;
    UIAlertController *alertSheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.navigationBar.translucent = NO;
    imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    imagePickerController.allowsEditing = YES;
    
    // 判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 设置数据源
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertSheet addAction:cameraAction];
    }
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }];
        [alertSheet addAction:photoAction];
    }
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertSheet addAction:cancelAction];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alertSheet animated:YES completion:nil];
    });
    
    
}



#pragma mark UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"])        // 被选中的图片
    {
        // 获取照片
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        [picker dismissViewControllerAnimated:YES completion:nil];          // 隐藏视图
        
        [self commitUserAvatarDataWithImage:image];
    }
}

#pragma mark  提交用户头像
-(void)commitUserAvatarDataWithImage:(UIImage *)image{
    
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:@"arr" forKey:@"ince"];
    [dic setValue:[UserHandle shareInstance].userId forKey:@"sid"];
    
    [self showHUD];
    [BSDNetTool requestAFURL:kHost parameters:dic imageData:imageData succeed:^(NSDictionary *data) {
        [self hidHUD];
        NSLog(@"data = %@",data);
        NSInteger flag = [[data objectForKey:@"ret"]integerValue];
        if(flag == 200){
            
            ShowMessage(data[@"msg"]);
            
            NSString *original = data[@"original_img"];
            NSString *url = data[@"url"];
            NSString *goods = data[@"goods_img"];
            
            NSDictionary* arg =  @{@"ince":@"update_goods_img",
                                   @"sid":[UserHandle shareInstance].userId,
                                   @"goods_id": self.currentGoods.fid,
                                   @"url":url,
                                   @"goods_img":goods,
                                   @"original_img":original
                                   };
            [BSDNetTool PostURL:kHost  parameters:arg succeed:^(NSDictionary *data) {
                NSLog(@"data = %@",data);
                NSInteger flag = [[data objectForKey:@"ret"]integerValue];
                if(flag == 200){
                    ShowMessage(data[@"msg"]);
                    NSString* iamge = [data objectForKey: @"goods_img"];
                    self.currentGoods.default_image = iamge;
                    [self.tableView reloadData];
                    
                }else{
                    ShowMessage(data[@"msg"]);
                }
                
            } failure:^(NSError *error) {
                [self alertHUD:@"网络异常"];
            }];
            
        }else{
            ShowMessage(data[@"msg"]);
        }
    
    } failure:^(NSError *error) {
        [self hidHUD:@"网络异常"];
    }];
    
}


#pragma mark - 懒加载

-(NSMutableArray *)selectedArray{
    
    if (!_selectedArray) {
        _selectedArray = [[NSMutableArray alloc]init];
        
    }
    
    return  _selectedArray;
}
-(Pager *)page{
    if(!_page){
        _page = [[Pager alloc]init];
        _page.pageIndex = 1;
    }
    return _page;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
